<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="车&nbsp;&nbsp;牌&nbsp;&nbsp;号" prop="licensePlateNumber">
              <el-input v-model="queryParams.licensePlateNumber" placeholder="请输入车牌号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="租赁状态" prop="leaseStatus">
              <el-select v-model="queryParams.leaseStatus" placeholder="请选择租赁状态" clearable>
                <el-option v-for="dict in car_lease_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="车辆品牌" prop="vehicleBrand">
              <el-input v-model="queryParams.vehicleBrand" placeholder="请输入车辆品牌" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="承&nbsp;&nbsp;租&nbsp;&nbsp;人" prop="rentHolder">
              <el-input v-model="queryParams.rentHolder" placeholder="请输入车辆品牌" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <div style="text-align: right">
          <el-button type="warning" icon="Download" @click="handleExport">导出</el-button>
          <el-button plain icon="Plus" @click="handelOpen('create')">新增</el-button>
          <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
        </div>
      </template>

      <el-table v-loading="loading" :data="carbasicInformationList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键标识" align="center" prop="id" v-if="false" />
        <el-table-column label="序号" align="center">
          <template #default="scope">{{ scope.$index + 1 }}</template>
        </el-table-column>
        <el-table-column label="车&nbsp;&nbsp;牌&nbsp;&nbsp;号" align="center" prop="licensePlateNumber" />
        <el-table-column label="车辆类型" align="center" prop="vehicleType">
          <template #default="scope">
            <dict-tag :options="car_vehicle_type" :value="scope.row.vehicleType" />
          </template>
        </el-table-column>
        <el-table-column label="所&nbsp;&nbsp;有&nbsp;&nbsp;人" align="center" prop="possessor" />
        <el-table-column label="租赁状态" align="center" prop="leaseStatus">
          <template #default="scope">
            <dict-tag :options="car_lease_status" :value="scope.row.leaseStatus" />
          </template>
        </el-table-column>
        <el-table-column label="动力类型" width="120" align="center" prop="dynamicType">
          <template #default="scope">
            <dict-tag :options="car_dynamic_type" :value="scope.row.dynamicType" />
          </template>
        </el-table-column>
        <el-table-column label="车辆品牌" align="center" prop="vehicleBrand" />
        <el-table-column label="型&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号" align="center" prop="modeNumber" />
        <el-table-column label="承租人" align="center" prop="rentHolder" />
        <el-table-column label="折合日租金" width="120" align="center" prop="equivalentDailyRent" />
        <el-table-column label="开始日期" width="120" align="center" prop="startTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束日期" width="120" align="center" prop="endTime">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="到期提醒" align="center" prop="expirationReminder" />

        <el-table-column fixed="right" width="120" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" @click="handelOpen('update', scope.row.carRentalInfoId, scope.row.id)"> 编辑 </el-button>
            <el-button link type="primary" @click="handelOpen('detail', scope.row.carRentalInfoId, scope.row.id)"> 详情 </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <formDialog ref="formRef" @getList="getList" />
    <!-- 添加或修改汽车基础信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1200px" append-to-body>
      <div class="kuaicenter">
        <div class="kuai"></div>
        <h2>基础信息</h2>
      </div>
      <el-form ref="carbasicInformationFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="车&nbsp;&nbsp;牌&nbsp;&nbsp;号" prop="licensePlateNumber">
              <el-input v-model="form.licensePlateNumber" placeholder="请输入车牌号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车辆类型" prop="vehicleType">
              <el-select v-model="form.vehicleType" placeholder="请选择车辆类型">
                <el-option v-for="dict in car_vehicle_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所&nbsp;&nbsp;有&nbsp;&nbsp;人" prop="possessor">
              <el-input v-model="form.possessor" placeholder="请输入所有人" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="租赁状态" prop="leaseStatus">
              <el-select v-model="form.leaseStatus" placeholder="请选择租赁状态">
                <el-option v-for="dict in car_lease_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="动力类型" prop="dynamicType">
              <el-select v-model="form.dynamicType" placeholder="请选择动力类型">
                <el-option v-for="dict in car_dynamic_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车辆品牌" prop="vehicleBrand">
              <el-input v-model="form.vehicleBrand" placeholder="请输入车辆品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="型&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号" prop="modeNumber">
              <el-input v-model="form.modeNumber" placeholder="请输入型号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="识别代码" prop="identificationCode">
              <el-input v-model="form.identificationCode" placeholder="请输入识别代码" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="注册日期" prop="registration">
              <el-date-picker clearable v-model="form.registration" type="date" value-format="YYYY-MM-DD" placeholder="请选择注册日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="下次年审日期" prop="nextAnnualInspectionDate">
              <el-date-picker clearable v-model="form.nextAnnualInspectionDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择下次年审日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="核定载人数" prop="authorizedCapacity">
              <el-input v-model="form.authorizedCapacity" placeholder="请输入核定载人数" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="购买金额" prop="purchaseAmount">
              <el-input v-model="form.purchaseAmount" placeholder="请输入购买金额" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="车辆估值" prop="vehicleValuation">
              <el-input v-model="form.vehicleValuation" placeholder="请输入车辆估值" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="kuaicenter">
        <div class="kuai"></div>
        <h2>租赁信息</h2>
      </div>
      <el-form ref="carrentalInfoFormRef" :model="carRentalInfoForm" :rules="rules" label-width="100px">
        <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item label="承&nbsp;&nbsp;租&nbsp;&nbsp;人" prop="associate">
              <el-input v-model="carRentalInfoForm.name" placeholder="请输入承租人" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联  系 人" prop="associate">
              <el-input v-model="carRentalInfoForm.associate" placeholder="请输入联  系 人" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式" prop="contactInformation">
              <el-input v-model="carRentalInfoForm.contactInformation" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="缴租频次" prop="frentPaymentFrequency">
              <el-select v-model="carRentalInfoForm.frentPaymentFrequency" placeholder="请选择缴租频次">
                <el-option v-for="dict in park_frent_payment_frequency" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable v-model="carRentalInfoForm.startTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable v-model="carRentalInfoForm.endTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="退租时间" prop="rentOutTime">
              <el-date-picker clearable v-model="carRentalInfoForm.rentOutTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择退租时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="退租类型" prop="rentOutStatus">
              <el-select v-model="carRentalInfoForm.rentOutStatus" placeholder="请选择退租类型">
                <el-option v-for="dict in park_surrender_tenancy_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="租赁总额" prop="totalLease">
              <el-input v-model="carRentalInfoForm.totalLease" placeholder="请输入租赁总额" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="已收金额" prop="amountReceived">
              <el-input v-model="carRentalInfoForm.amountReceived" placeholder="请输入已收金额" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="欠款金额" prop="amountDue">
              <el-input v-model="carRentalInfoForm.amountDue" placeholder="请输入欠款金额" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="折合日租金" prop="equivalentDailyRent">
              <el-input v-model="carRentalInfoForm.equivalentDailyRent" placeholder="请输入折合日租金" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <div>表单数据: {{form}}</div>
  </div>
</template>

<script setup name="CarbasicInformation" lang="ts">
import {
  listCarbasicInformation,
  getCarbasicInformation,
  delCarbasicInformation,
  addCarbasicInformation,
  updateCarbasicInformation
} from '@/api/zichanguanli/carbasicInformation/index';
import { CarbasicInformationVO, CarbasicInformationQuery, CarbasicInformationForm } from '@/api/zichanguanli/carbasicInformation/types';
import { listCarrentalInfo, getCarrentalInfo, delCarrentalInfo, addCarrentalInfo, updateCarrentalInfo } from '@/api/zichanguanli/carrentalInfo/index';
import { CarrentalInfoVO, CarrentalInfoQuery, CarrentalInfoForm } from '@/api/zichanguanli/carrentalInfo/types';
import formDialog from './form.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { car_vehicle_type, car_dynamic_type, car_lease_status, park_surrender_tenancy_status, park_frent_payment_frequency } = toRefs<any>(
  proxy?.useDict('car_vehicle_type', 'car_dynamic_type', 'car_lease_status', 'park_surrender_tenancy_status', 'park_frent_payment_frequency')
);

const carbasicInformationList = ref<CarbasicInformationVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const carbasicInformationFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const formRef = ref();
const handelOpen = (type: string, carRentalInfoId?: string | number, automobileBasicInfoId?: string | number) => {
  formRef.value.open(type, carRentalInfoId, automobileBasicInfoId);
};

const initFormData: CarbasicInformationForm = {
  id: undefined,
  licensePlateNumber: undefined,
  vehicleType: undefined,
  possessor: undefined,
  leaseStatus: undefined,
  dynamicType: undefined,
  vehicleBrand: undefined,
  modeNumber: undefined,
  identificationCode: undefined,
  registration: undefined,
  nextAnnualInspectionDate: undefined,
  authorizedCapacity: undefined,
  purchaseAmount: undefined,
  vehicleValuation: undefined
};

const initCarRentalInfoFormData: CarrentalInfoForm = {
  id: undefined,
  automobileBasicInformationId: undefined,
  name: undefined,
  associate: undefined,
  contactInformation: undefined,
  frentPaymentFrequency: undefined,
  startTime: undefined,
  endTime: undefined,
  rentOutTime: undefined,
  rentOutStatus: undefined,
  totalLease: undefined,
  amountReceived: undefined,
  amountDue: undefined,
  equivalentDailyRent: undefined
};
const carRentalInfoForm = ref<CarrentalInfoForm>();
carRentalInfoForm.value = { ...initCarRentalInfoFormData };

const validateNumber = (rule: any, value: any, callback: any) => {
  if (value === '' || value === undefined || value === null) {
    callback();
    return;
  }
  const reg = /^\d+(\.\d{1,2})?$/;
  if (!reg.test(value)) {
    callback(new Error('请输入数字，最多保留两位小数'));
  } else {
    callback();
  }
};

const validateInteger = (rule: any, value: any, callback: any) => {
  if (value === '' || value === undefined || value === null) {
    callback();
    return;
  }
  const reg = /^[1-9]\d*$/;
  if (!reg.test(value)) {
    callback(new Error('请输入正整数'));
  } else {
    callback();
  }
};

const data = reactive<PageData<CarbasicInformationForm, CarbasicInformationQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    licensePlateNumber: undefined,
    leaseStatus: undefined,
    vehicleBrand: undefined,
    rentHolder: undefined
  },
  rules: {
    id: [{ required: true, message: '主键标识不能为空', trigger: 'blur' }],
    licensePlateNumber: [
      { required: true, message: '车牌号不能为空', trigger: 'blur' },
      {
        pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/,
        message: '请填写正确的车牌号',
        trigger: 'change'
      }
    ],
    vehicleType: [{ required: true, message: '车辆类型不能为空', trigger: 'change' }],
    possessor: [{ required: true, message: '所有人不能为空', trigger: 'blur' }],
    leaseStatus: [{ required: true, message: '租赁状态不能为空', trigger: 'change' }],
    dynamicType: [{ required: true, message: '动力类型不能为空', trigger: 'change' }],
    vehicleBrand: [{ required: true, message: '车辆品牌不能为空', trigger: 'blur' }],
    modeNumber: [{ required: true, message: '型号不能为空', trigger: 'blur' }],
    identificationCode: [{ required: true, message: '识别代码不能为空', trigger: 'blur' }],
    registration: [{ required: true, message: '注册日期不能为空', trigger: 'blur' }],
    nextAnnualInspectionDate: [{ required: true, message: '下次年审日期不能为空', trigger: 'blur' }],
    authorizedCapacity: [{ validator: validateInteger, trigger: 'change' }],
    purchaseAmount: [{ validator: validateNumber, trigger: 'change' }],
    vehicleValuation: [{ validator: validateNumber, trigger: 'change' }],
    contactInformation: [
      {
         required: true,
        message: '请填写正确的手机号码',
        trigger: 'change'
      }
    ],
    totalLease: [{ validator: validateNumber, trigger: 'change' }],
    amountReceived: [{ validator: validateNumber, trigger: 'change' }],
    amountDue: [{ validator: validateNumber, trigger: 'change' }],
    equivalentDailyRent: [{ validator: validateNumber, trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询汽车基础信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCarbasicInformation(queryParams.value);
  carbasicInformationList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  carbasicInformationFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: CarbasicInformationVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加汽车基础信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: CarbasicInformationVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getCarbasicInformation(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改汽车基础信息';
};

/** 提交按钮 */
const submitForm = () => {
  carbasicInformationFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateCarbasicInformation(form.value).finally(() => (buttonLoading.value = false));
        if (Object.keys(carRentalInfoForm.value).length === 0) {
          carRentalInfoForm.value.automobileBasicInformationId = form.value.id;
          await addCarrentalInfo(carRentalInfoForm.value);
        }
        if (Object.keys(carRentalInfoForm.value).length > 0) {
          carRentalInfoForm.value.automobileBasicInformationId = form.value.id;
          await updateCarrentalInfo(carRentalInfoForm.value);
        }
      } else {
        const res = await addCarbasicInformation(form.value);
        //carRentalInfoForm不为空
        if (Object.keys(carRentalInfoForm.value).length > 0) {
          carRentalInfoForm.value.automobileBasicInformationId = res.data;
          await addCarrentalInfo(carRentalInfoForm.value);
        }
      }
      buttonLoading.value = false;
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: CarbasicInformationVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('确定删除所选的信息吗？').finally(() => (loading.value = false));
  await delCarbasicInformation(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'zichanguanli/carbasicInformation/export',
    {
      ...queryParams.value
    },
    `carbasicInformation_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
